var context;
var basePath = (function () {
    var url = window.location + "";
    var h = url.split("//");
    var x = h[1].split("/");
    context = x[1];
    return h[0] + "//" + window.location.host + "/" + x[1] + "/";
})();
$(function () {
    $.when(customGlobal.initMenu())
        .done(function(){
            $("#menu_" + $("#menuParentId").val()).addClass("active").find("span.arrow").addClass("open");
            $("#menu_" + $("#menuId").val()).addClass("active");
            Metronic.init(); // init metronic core components
            Layout.init(); // init current layout
            $.gAuto();
            $.iTypeInit();
            var $menuSearch = $("#menuSearch").on("keydown",function(e){
                var $this = $(this);
                var menuId = $this.getGAutoHiddenValue();
                if (e.which == 13 && menuId != undefined && menuId != "") {
                    e.preventDefault();
                    customGlobal.menuSearch(menuId);
                }
            });
            $("#menuSearchBtn").on("click",function(){
                var menuId = $menuSearch.getGAutoHiddenValue();
                if (menuId != undefined && menuId != "") {
                    customGlobal.menuSearch(menuId)
                }
            });
        });
    //此函数为了处理firefox及chrome中，在弹出的窗口中点击ckeditor的上传图片，显示的input无法获取光标的问题
    $.fn.modal.Constructor.prototype.enforceFocus = function() {
        modal_this = this;
        $(document).on('focusin.modal', function (e) {
            if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length
                && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select')
                && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) {
                modal_this.$element.focus()
            }
        })
    };
    $.ajaxSetup({
        cache: false,
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            if(XMLHttpRequest.responseJSON){
                toast.error(XMLHttpRequest.responseJSON.returnMsg);
            }else {
                toast.error("state：" + XMLHttpRequest.status + ", error：" + XMLHttpRequest.statusText)
            }
            Metronic.unblockUI(customGlobal.blockUITarget);
        }
    });
    $.validator.setDefaults({
        errorElement: 'span', //default input error message container
        errorClass: 'help-block help-block-error', // default input error message class
        focusInvalid: true,
        ignore: "",  // validate all fields including form hidden input
        highlight: function (element) { // hightlight error inputs
            $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
        },
        unhighlight: function (element) { // revert the change done by hightlight
            $(element).closest('.form-group').removeClass('has-error'); // set error class to the control group
        },
        success: function (label) {
            label.closest('.form-group').removeClass('has-error'); // set success class to the control group
        },
        invalidHandler: function (event, validator) { //display error alert on form submit
            toastr.error(i18n["tableWrong"]);
        },
        errorPlacement: function (error, element) { // render error placement for each input type
            if (element.attr("data-error-container")) {
                error.appendTo(element.attr("data-error-container"));
            }else if (element.parents('.radio-list').size() > 0) {
                error.appendTo(element.parents('.radio-list').attr("data-error-container"));
            }else if (element.parents('.checkbox-list').size() > 0) {
                error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
            }else {
                error.insertAfter(element); // for other inputs, just perform default behavior
            }
        }
    });
    $.validator.messages.equalTo=i18n["diffInput"];
    customGlobal.initUpdatePasswordEvent();
});
var customGlobal = {
    onSortColumnDefault: function (sortColumn, sortDirection) {
        sortColumn = sortColumn.replace(/([A-Z])/g,"_$1").toLowerCase();
        return {
            sortColumn: sortColumn,
            sortDirection: sortDirection
        }
    },
    blockUI:function(target){
        if (target!==undefined) {
            customGlobal.blockUITarget = target;
            Metronic.blockUI({
                target: target,
                boxed: true,
                message: i18n["loading"]
            });
        }else{
            Metronic.blockUI({
                boxed: true,
                message: i18n["loading"]
            });
        }
    },
    ajaxCallback:function(data){
        Metronic.unblockUI(customGlobal.blockUITarget);
        if(data.ok){
            toast.success(data.returnMsg);
            return true;
        }else if(data.error){
            toast.error(data.returnMsg);
            return false;
        }else if(data.warning){
            toast.warning(data.returnMsg);
            return true;
        }
    },
    clearFormAndShowDialog :function(dialogId){
        $("#"+dialogId).find("input:text,input:password,select,textarea").val("").end().modal("show").find("div.form-group").removeClass("has-error");
    },
    menuSearch:function(menuId){
        $.post("develop/menu/menuSearch",{menuId:menuId})
            .done(function (data) {
                if (data.ok) {
                    location.href = data.returnData.url;
                } else if (data.error) {
                    toast.error(data.returnMsg);
                    return false;
                }
            })
    },
    initUpdatePasswordEvent:function () {
        $("#updatePass").on("click",function(){
            $("#updatePasswordModal").html(customGlobal.remoteTemplate("template/core/common/updatePassword.html", {})).modal("show");
            $("#updatePassword").on("click",function(){
                if (!$("#updatePasswordDialog").validate().form()){
                    return;
                }
                customGlobal.blockUI("#updatePasswordContent");
                $.ajax({
                    url: "security/user/updatePassword",
                    data: {
                        oldPassword: $("#oldPassword").val().md5(),
                        newPassword: $("#newPassword").val().md5()
                    },
                    type: "post",
                    dataType:"json"
                }).done(function (data) {
                    if (customGlobal.ajaxCallback(data)) {
                        $("#updatePasswordModal").modal("hide");
                    }
                })
            });
        });
    },
    /**
     * 通过html导出excel
     * @param colNum excel的列数
     * @param rowNum excel标题+表头的行数
     * @param htmlObj 包含要导出数据html的jquery对象
     * @param excelVersion excel版本包括（xls,xlsx）
     */
    exportByHtml:function(colNum,rowNum,htmlObj,excelVersion){
        colNum = colNum == undefined ? $("#colNum").val() : colNum;
        if(colNum>254){
            excelVersion="xlsx"
        }
        rowNum = rowNum == undefined ? $("#rowNum").val() : rowNum;
        rowNum = rowNum == undefined ? 2 : rowNum;
        htmlObj = htmlObj == undefined ? $("#dataListDiv"): htmlObj;
        excelVersion = excelVersion == undefined ? $("#excelVersion").val() : excelVersion;
        excelVersion = excelVersion == undefined ? "xls" : excelVersion;

        var form = $("<form>").attr('style','display:none').attr('target','_self').attr('method','post')
            .attr('action',basePath + "exportExcel/exportExcelByHtml");
        var colNumObj = $('<input>').attr('type','hidden').attr('name','colNum').val(colNum);
        var rowNumObj = $('<input>').attr('type','hidden').attr('name','tableHeadRowNum').val(rowNum);
        var htmlStrObj = $('<input>').attr('type','hidden').attr('name','htmlStr').val(htmlObj.html());
        var excelVersionObj = $('<input>').attr('type','hidden').attr('name','excelVersion').val(excelVersion);
        $('body').append(form);
        form.append(colNumObj).append(rowNumObj).append(htmlStrObj).append(excelVersionObj).submit().remove();
    },
    /**
     * 通过后台导出excel
     * @param url
     * @param data
     */
    formSubExport:function(url,data){
        var form = $("<form>").attr('style','display:none').attr('target','_self').attr('method','post')
            .attr('action',basePath + url);
        $('body').append(form);
        for(var i=0;i< data.length;i++){
            var inputStr=$('<input>').attr('type','hidden').attr('name',data[i].name).val(data[i].value);
            form.append(inputStr)
        }
        form.submit().remove();
    },
    getQueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null)return decodeURI(r[2]);
        return null;
    },
    templateCache: {},
    remoteTemplate: function (url, data) {
        var render = customGlobal.templateCache[url];
        if (render == undefined || render == null) {
            $.ajax({
                url: basePath + url,
                dataType:"html",
                type: "get",
                async: false
            }).done(function (html) {
                render = template.compile(html);
                customGlobal.templateCache[url] = render;
            });
        }
        data.i18n = i18n;
        return render(data);
    },
    showConfirm: function (param) {
        var defaultData = {
            confirmTitle: i18n.confirm,
            confirmContent: i18n.deletePrompt,
            confirmBtn: i18n.confirm,
            cancelBtn: i18n.cancel,
            confirmDialogId: "confirmDialog",
            confirmBtnId: "confirmBtn",
            confirmDialogWrapperId: "confirmDialogWrapper"
        };
        var data = $.extend(true, {}, defaultData, param);
        if ($("#"+data.confirmDialogWrapperId).size() == 0) {
            $("body").append("<div id='"+data.confirmDialogWrapperId+"'></div>")
        }
        $("#"+data.confirmDialogWrapperId).html(customGlobal.remoteTemplate("template/core/common/confirm.html", data));
        $("#"+data.confirmDialogId).modal("show")
    },
    initMenu: function () {
        var dtd = $.Deferred();
        var $sidebarWrapper = $("#sidebarWrapper");
        if ($sidebarWrapper.size() == 1) {
            //requestNo为判断当前是否是第一次载入菜单用的，在sidebar.jsp中声明的。
            if (requestNo > 1) {
                $sidebarWrapper.html(localStorage[context+"SidebarHtml"]);
                dtd.resolve();
            } else {
                $.ajax({
                    url: basePath + "develop/menu/sidebarData",
                    dataType: "json",
                    type: "get"
                }).done(function (data) {
                    var sidebarData = data.returnData;
                    sidebarData.basePath = basePath;
                    var sidebarHtml = customGlobal.remoteTemplate("template/core/common/sidebar.html", sidebarData);
                    localStorage[context+"SidebarHtml"] = sidebarHtml;
                    $sidebarWrapper.html(sidebarHtml);
                    dtd.resolve();
                });
            }
        }
        return dtd.promise();
    },
    generalClass:{
        0:"label-danger",
        1:"label-success"
    }
};
